package com.asiainfo.ncrm;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;
import cn.com.senter.sdkdefault.helper.b;

import com.asiainfo.ncrm.base.BaseHttp;
import com.asiainfo.ncrm.base.HttpCallBack;
import com.asiainfo.ncrm.base.Result;
import com.asiainfo.ncrm.bean.UserInfo;
import com.asiainfo.ncrm.common.Constant;
import com.asiainfo.ncrm.pulltozoom.PullToZoomScrollViewEx;
import com.asiainfo.ncrm.util.CustomProgressDialog;
import com.asiainfo.ncrm.util.MD5Helper;
import com.google.gson.reflect.TypeToken;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


/**
 * Author:    ZhuWenWu
 * Version    V1.0
 * Date:      2014/9/4  17:30.
 * Description:
 * Modification  History:
 * Date         	Author        		Version        	Description
 * -----------------------------------------------------------------------------------
 * 2014/9/4        ZhuWenWu            1.0                    1.0
 * Why & What is modified:
 */
public class PullToZoomScrollActivity extends MainActivity {

    private PullToZoomScrollViewEx scrollView;
    
    private EditText textname = null;
	private EditText pwd = null;
	private Button login = null;
	
	private EditText smsCode1 = null;
	private EditText smsCode2 = null;
	
	private EditText phone_text= null;
	
	private Button sendSms = null ; //发送短信验证码
	
	private Button login_sms= null;//短信登录的按钮
	
	View headView =null;
    View zoomView = null;
    View contentView = null;
    
    TextView tv_register;
    
    TextView tv_login;
	
    private Context mContext;
	
	private int mode =1;//1账户密码登录2短信登录
	
	protected BaseHttp bh ;
	
	private String linkPhone;
	
	private CustomProgressDialog customDialog;
	
	private String userno = "";
	private String password = "";
	private String staffNumber = "";
	private String olNbr = "";
	private String sign = "";
	private String sysCode = "";
	private String data = "";
	
	private Button btGetVerificationCode;  
	private Button btRegister;  
	private boolean result = true;  
	private int time = 60;  
	private int count = 0;  
	
	private String checkSMScode= "";
	
	

    /* （非 Javadoc）
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_pull_to_zoom_scroll_view);
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        loadViewForCode();
        scrollView = (PullToZoomScrollViewEx) findViewById(R.id.scroll_view);
        DisplayMetrics localDisplayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(localDisplayMetrics);
        int mScreenHeight = localDisplayMetrics.heightPixels;
        int mScreenWidth = localDisplayMetrics.widthPixels;
        LinearLayout.LayoutParams localObject = new LinearLayout.LayoutParams(mScreenWidth, (int) (9.0F * (mScreenWidth / 16.0F)));
        scrollView.setHeaderLayoutParams(localObject);
       
        setView();
        
    }
    
    private void setView (){
    	
    	bh= new BaseHttp(this);
    	
    	 tv_register = (TextView) this.findViewById(R.id.tv_register);
    	
    	 tv_login = (TextView) this.findViewById(R.id.tv_login);
    	 
    	 textname=  (EditText) this.findViewById(R.id.login_text);
 		pwd = (EditText)this.findViewById(R.id.login_pwd);
    	
    	tv_register.setOnClickListener( new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO 自动生成的方法存根
				if(mode != 1){
					mode =1;
					
					tv_register.setTextColor(Color.rgb(44, 193, 84));
					tv_login.setTextColor(Color.rgb(255, 255, 255));
					contentView = LayoutInflater.from(mContext).inflate(R.layout.login_3, null, false);
					scrollView.setScrollContentView(contentView);
				}
			}
		});
    	
    	tv_login.setOnClickListener( new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO 自动生成的方法存根
				if(mode != 2){
					mode =2;
					
					tv_register.setTextColor(Color.rgb(255, 255, 255));
					tv_login.setTextColor(Color.rgb(44, 193, 84));
					contentView = LayoutInflater.from(mContext).inflate(R.layout.login_duanxin, null, false);
					scrollView.setScrollContentView(contentView);
					
					loginMsg();
					
				}
			}
		});
    	
    	login = (Button) this.findViewById(R.id.tologin);
    	
    	smsCode1 = (EditText)this.findViewById(R.id.smsCode1);
    	
    	
		login.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
					if(smsCode1.getVisibility() == View.GONE){
						
					
					
					String staffcode= textname.getText().toString();
					String codepwd = pwd.getText().toString();
					
					if((staffcode == null || "".equals(staffcode))|| (codepwd == null || "".equals(codepwd)) ){
						Toast.makeText(mContext, "账户密码为空", Toast.LENGTH_LONG).show();
						return;
					}
					//调用http协议
					String path=Constant.OUTURL+"/BizHall/superSo/loginByAndroid";
					try {
	
						/*封装Person数组*/
						/*把JSON数据转换成String类型使用输出流向服务器写*/
						String content ="{staffCode:"+URLEncoder.encode(staffcode,"utf-8")+",password:"+URLEncoder.encode(codepwd,"utf-8")+"}";
						
						Map<String,Object> mymap = new HashMap<String, Object>();
						mymap.put("staffCode", URLEncoder.encode(staffcode,"utf-8"));
						mymap.put("password", URLEncoder.encode(codepwd,"utf-8"));
						
						userno =  URLEncoder.encode(staffcode,"utf-8");
						password = URLEncoder.encode(codepwd,"utf-8");
						
						path= path+"?staffCode="+URLEncoder.encode(staffcode,"utf-8")+"&password="+URLEncoder.encode(codepwd,"utf-8")+"&"+(new Date()).getTime();
						
						bh.post(path,null, new TypeToken<Result<UserInfo>>() {
						});
						
						bh.callBack(new HttpCallBack() {
	
							@Override
							public <T> void onSuccess(String msg, T result) {
								// TODO 自动生成的方法存根
								//保存用户名密码
	//							saveLoginInfo(mContext,userno,password);
								
								UserInfo user = (UserInfo) result;
								
								if(user.getSMS()!=null && !"".equals(user.getSMS())){//存在跳过短信验证的权限
								
									if(!user.getSTAFF_CODE().equals("")){
										Intent i = new Intent();
										i.putExtra("staffCode",userno );
										i.putExtra("password",password );
						            	i.setClass(mContext, HomeActivity.class);
						            	mContext.startActivity(i);
									}
									
									Toast.makeText(mContext, "登录成功", Toast.LENGTH_LONG).show();
								}else{
									smsCode1.setVisibility(View.VISIBLE);
									Toast.makeText(mContext, "请输入短信验证码", Toast.LENGTH_LONG).show();
									
									checkSMScode = user.getMd5Pwd();
									
								}
								
								
							}
	
							@Override
							public <T> void onFailure(String msg, T result) {
								// TODO 自动生成的方法存根
								Toast.makeText(mContext, "登录失败", Toast.LENGTH_LONG).show();
							}
							
						});
					} catch (Exception e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
				}else{
					String code = smsCode1.getText().toString();
					if("".equals( code)){
						Toast.makeText(mContext, "请输入短信验证码", Toast.LENGTH_LONG).show();
						return;
					}else{
						String mdx = MD5Helper.getMD5Str(code);
						
						if(checkSMScode.equals(mdx)){///假如验证码校验通过
							
							
							String staffcode= textname.getText().toString();
							String codepwd = pwd.getText().toString();
							
							if((staffcode == null || "".equals(staffcode))|| (codepwd == null || "".equals(codepwd)) ){
								Toast.makeText(mContext, "账户密码为空", Toast.LENGTH_LONG).show();
								return;
							}
							//调用http协议
							String path=Constant.OUTURL+"/BizHall/superSo/loginByAndroid";
							try {
			
								/*封装Person数组*/
								/*把JSON数据转换成String类型使用输出流向服务器写*/
								String content ="{staffCode:"+URLEncoder.encode(staffcode,"utf-8")+",password:"+URLEncoder.encode(codepwd,"utf-8")+"}";
								
								Map<String,Object> mymap = new HashMap<String, Object>();
								mymap.put("staffCode", URLEncoder.encode(staffcode,"utf-8"));
								mymap.put("password", URLEncoder.encode(codepwd,"utf-8"));
								
								userno =  URLEncoder.encode(staffcode,"utf-8");
								password = URLEncoder.encode(codepwd,"utf-8");
								
								path= path+"?staffCode="+URLEncoder.encode(staffcode,"utf-8")+"&password="+URLEncoder.encode(codepwd,"utf-8")+"&"+(new Date()).getTime();
								
								bh.post(path,null, new TypeToken<Result<UserInfo>>() {
								});
								
								bh.callBack(new HttpCallBack() {
			
									@Override
									public <T> void onSuccess(String msg, T result) {
										// TODO 自动生成的方法存根
										//保存用户名密码
			//							saveLoginInfo(mContext,userno,password);
										
										UserInfo user = (UserInfo) result;
										
											if(!user.getSTAFF_CODE().equals("")){
												Intent i = new Intent();
												i.putExtra("staffCode",userno );
												i.putExtra("password",password );
								            	i.setClass(mContext, HomeActivity.class);
								            	mContext.startActivity(i);
											}
											
											Toast.makeText(mContext, "登录成功", Toast.LENGTH_LONG).show();
										
										
									}
			
									@Override
									public <T> void onFailure(String msg, T result) {
										// TODO 自动生成的方法存根
										Toast.makeText(mContext, "登录失败", Toast.LENGTH_LONG).show();
									}
									
								});
							} catch (Exception e) {
								// TODO 自动生成的 catch 块
								e.printStackTrace();
							}
							
							
						}else{
							Toast.makeText(mContext, "短信验证码不正确", Toast.LENGTH_LONG).show();
							return;
							
						}
					}
				}
				
			}
		});
		
		
		
    }
    
    
    public void loginMsg(){
    	Activity activity = (Activity) mContext;
		//主动发送短信方法
		sendSms =  (Button) activity.findViewById(R.id.sendSms);
		
		login_sms= (Button) activity.findViewById(R.id.login_sms);
		
		phone_text = (EditText) activity.findViewById(R.id.phone_text);
		
		smsCode2 = (EditText) activity.findViewById(R.id.smsCode2);
		
		sendSms.setOnClickListener(new OnClickListener() {
		
			@Override
			public void onClick(View v) {
				
				try {
					
					String receiver = phone_text.getText().toString();
					if(receiver == "" ){
						
						Toast.makeText(mContext, "手机号码为空", Toast.LENGTH_LONG).show();
						
						return;
					}
					Map<String,Object> mymap = new HashMap<String, Object>();
					String path=Constant.OUTURL+"/BizHall/custQuery/sendMsgCheckNum";
					 path += "?jsonStr={\"userNo\":20985,\"sender\":\"CRM\",\"receiver\":\""+receiver+"\",\"partyId\":\"\",\"routeParam\":{\"areaId\":10104}}";
					
					bh.post(path,null, new TypeToken<Result<String>>() {
					});
					
					bh.callBack(new HttpCallBack() {

						@Override
						public <T> void onSuccess(String msg, T result) {
								showTime();
								Toast.makeText(mContext, "发送短信成功", Toast.LENGTH_LONG).show();
								
								JSONObject json = (JSONObject) result;
								if(json.containsKey("md5Pwd")){
									checkSMScode= json.getString("md5Pwd");//保存验证码
								}
								
							
						}

						@Override
						public <T> void onFailure(String msg, T result) {
							// TODO 自动生成的方法存根
							Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
						}
						
					});
				} catch (Exception e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
				
				
				
				
			}
		});
		
		login_sms.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
					String code = phone_text.getText().toString();
					
					if(code == "" ){
						
						Toast.makeText(mContext, "请填写手机验证码", Toast.LENGTH_LONG).show();
						
						return;
					}
					
					//先校验短信验证码是否一致
					String mdx = MD5Helper.getMD5Str(code);
					
					if(checkSMScode.equals(mdx)){///假如验证码校验通过
						//做登录
						String receiver = phone_text.getText().toString();
						String path=Constant.OUTURL+"/BizHall/superSo/loginByAndroid?linkPhone="+receiver;
						bh.post(path,null, new TypeToken<Result<UserInfo>>() {
						});
						
						bh.callBack(new HttpCallBack() {

							@Override
							public <T> void onSuccess(String msg, T result) {
								// TODO 自动生成的方法存根
								
								UserInfo user = (UserInfo) result;
								if(!user.getSTAFFNAME().equals("")){
									Intent i = new Intent();
									i.putExtra("linkPhone",linkPhone );
					            	i.setClass(mContext, HomeActivity.class);
					            	mContext.startActivity(i);
					            	Toast.makeText(mContext, "登录成功", Toast.LENGTH_LONG).show();
								}else{
									Toast.makeText(mContext, "登录失败", Toast.LENGTH_LONG).show();
								}
								
								
								
							}

							@Override
							public <T> void onFailure(String msg, T result) {
								// TODO 自动生成的方法存根
								Toast.makeText(mContext, "登录失败", Toast.LENGTH_LONG).show();
							}
							
						});
						
					
					}else{
						Toast.makeText(mContext, "验证码不正确", Toast.LENGTH_LONG).show();
						
						return;
					}
					
				
			}
		});
    }
    


    private void loadViewForCode() {
        PullToZoomScrollViewEx scrollView = (PullToZoomScrollViewEx) findViewById(R.id.scroll_view);
         headView = LayoutInflater.from(this).inflate(R.layout.profile_head_view, null, false);
         zoomView = LayoutInflater.from(this).inflate(R.layout.profile_zoom_view, null, false);
         contentView = LayoutInflater.from(this).inflate(R.layout.login_3, null, false);
        scrollView.setHeaderView(headView);
        scrollView.setZoomView(zoomView);
        scrollView.setScrollContentView(contentView);
    }
    
    
    
    //短信发送变黑
    /**  
     * 显示时间在梯减的文本框  
     */  
    public void showTime() {  
        new Thread(new Runnable() {  
            @Override  
            public void run() {  
                while (result) {  
                    time--;  
                    try {  
                        Thread.sleep(1000);  
//                                     tvShowTime.setText(time + "s后从新获取");  
                        sendSms.post(new Runnable() {  
                            @Override  
                            public void run() {  
                            	sendSms.setText(time + "s后重新获取");  
                            	sendSms.setClickable(false);  
                            	sendSms.setTextColor(Color.rgb(204, 204, 204));
//                                btGetVerificationCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.text_layout_bg_codenotedit));  
                            }  
                        });  
                        if (time <= 1) {  
                            count=0;  
                            result = false;  
                            sendSms.post(new Runnable() {  
                                @Override  
                                public void run() {  
                                	sendSms.setText("获取验证码");  
                                	sendSms.setClickable(true);  
                                    sendSms.setTextColor(Color.rgb(44, 193, 84));
//                                    btGetVerificationCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.selector_btn_red));  
                                }  
                            });  
                        }  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                }  
                result = true;  
                time = 60;  
            }  
        }).start();  
    } 
    
    
    
}
